local BrainCommon = require("brains/braincommon")

require "behaviours/panic"
require "behaviours/chaseandattack"
require "behaviours/wander"
require "behaviours/follow"
local MIN_FOLLOW_DIST = 2
local TARGET_FOLLOW_DIST = 5
local MAX_FOLLOW_DIST = 9
local START_FACE_DIST = 4
local KEEP_FACE_DIST = 6

local MoonNutDrakeBrain =
	Class(
	Brain,
	function(self, inst)
		Brain._ctor(self, inst)
	end
)

local function ExitAction(inst)
	if not inst:HasTag("exit") then
		inst:AddTag("exit")
		inst.sg:GoToState("idle")
		inst:DoTaskInTime(
			.3,
			function(inst)
				inst.sg:GoToState("exit")
			end
		)
	end
end

local function GetFaceTargetFn(inst)
	if
		not (inst.components.domesticatable ~= nil and inst.components.domesticatable:IsDomesticated()) and
			not BrainCommon.ShouldSeekSalt(inst)
	 then
		local target = FindClosestPlayerToInst(inst, START_FACE_DIST, true)
		return target ~= nil and not target:HasTag("notarget") and target or nil
	end
end

local function KeepFaceTargetFn(inst, target)
	return inst ~= nil and target ~= nil and inst:IsValid() and target:IsValid() and
		not (target:HasTag("notarget") or target:HasTag("playerghost")) and
		inst:IsNear(target, KEEP_FACE_DIST) and
		not BrainCommon.ShouldSeekSalt(inst)
end

function MoonNutDrakeBrain:OnStart()
	local root =
		PriorityNode(
		{
			WhileNode(
				function()
					return self.inst.components.health.takingfiredamage
				end,
				"OnFire",
				Panic(self.inst)
			),
			ChaseAndAttack(self.inst, 8, 14),
			Follow(self.inst, self.inst.components.follower.leader, MIN_FOLLOW_DIST, TARGET_FOLLOW_DIST, MAX_FOLLOW_DIST),
			FaceEntity(self.inst, GetFaceTargetFn, KeepFaceTargetFn),
			Wander(
				self.inst,
				function()
					if self.inst.components.follower.leader then
						return Vector3(self.inst.components.follower.leader.Transform:GetWorldPosition())
					end
				end,
				MAX_FOLLOW_DIST - 1,
				{minwalktime = .5, randwalktime = .5, minwaittime = 6, randwaittime = 3}
			),
			DoAction(self.inst, ExitAction, "exit", true)
		},
		0.25
	)

	self.bt = BT(self.inst, root)
end

return MoonNutDrakeBrain
